package cn.com.ghy.android.widget.visit;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.com.ghy.android.bean.DataCollectSaleInfoBean;
import cn.com.ghy.android.bean.SaleTypeBean;
import cn.com.ghy.android.bean.UnitInfoBean;
import cn.com.ghy.android.util.CommonUtil;
import cn.com.ghy.android.widget.R;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.Toast;
import android.widget.EditText;
import android.widget.Spinner;

public class DataCollectSale extends Activity {

	private EditText txtSKUId = null;
	private EditText txtApplyForSale = null;
	private EditText txtExecSale = null;
	private EditText txtEffect = null;

	private Spinner spiUnit = null;
	private Spinner spiSaleType = null;

	private Button btnStartDateModify = null;
	private Button btnEndDataModify = null;
	private Button btnSave = null;
	private Button btnBack = null;
	private CheckBox chkIsTG = null;
	private CheckBox chkIsSaleTablet = null;

	private Intent intent = null;
	private Bundle bundle = null;

	private List<DataCollectSaleInfoBean> dataCollectSaleInfoList = null;
	private List<UnitInfoBean> unitInfoList = null;
	private List<SaleTypeBean> saleTypeList = null;
	private String vsdate = null;
	private DataCollectSaleInfoBean dataCollectSaleInfo = null;
	private int mYear = 2011;
	private int mMonth = 0;
	private int mDay = 01;
	private String status = "add";
	private String oldSku = null;
	private int dataCollSalePosition = -1;

	@SuppressWarnings("unused")
	private static final String TAG = "DataCollectSale";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.data_collect_sale);
		getSession();
		findView();
		init();
		addListener();
	}

	@SuppressWarnings("unchecked")
	private void getSession() {
		bundle = this.getIntent().getExtras();
		unitInfoList = (List<UnitInfoBean>) bundle.getSerializable("unitInfoList");
		saleTypeList = (List<SaleTypeBean>) bundle.getSerializable("saleTypeList");
		vsdate = bundle.getString("vsdate");
		dataCollectSaleInfoList = (List<DataCollectSaleInfoBean>) bundle
				.getSerializable("dataCollectSaleInfoList");
		dataCollectSaleInfo = (DataCollectSaleInfoBean) bundle
				.getSerializable("dataCollectSaleInfo");
		dataCollSalePosition = bundle.getInt("dataCollSalePosition", -1);
	}

	private void findView() {
		txtSKUId = (EditText) this.findViewById(R.id.txtSKUId);
		txtApplyForSale = (EditText) this.findViewById(R.id.txtApplyForSale);
		txtExecSale = (EditText) this.findViewById(R.id.txtExecSale);
		txtEffect = (EditText) this.findViewById(R.id.txtEffect);

		spiUnit = (Spinner) this.findViewById(R.id.spiUnit);
		spiSaleType = (Spinner) this.findViewById(R.id.spiSaleType);

		btnStartDateModify = (Button) this.findViewById(R.id.btnStartDateModify);
		btnEndDataModify = (Button) this.findViewById(R.id.btnEndDataModify);
		btnSave = (Button) this.findViewById(R.id.btnSave);
		btnBack = (Button) this.findViewById(R.id.btnBack);
		chkIsTG = (CheckBox) this.findViewById(R.id.chkIsTG);
		chkIsSaleTablet = (CheckBox) this.findViewById(R.id.chkIsSaleTablet);
	}

	private void init() {
		ArrayAdapter<UnitInfoBean> unitInfoAdapter = new ArrayAdapter<UnitInfoBean>(
				DataCollectSale.this, android.R.layout.simple_spinner_item, unitInfoList);
		unitInfoAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spiUnit.setAdapter(unitInfoAdapter);

		ArrayAdapter<SaleTypeBean> saleTypeAdapter = new ArrayAdapter<SaleTypeBean>(
				DataCollectSale.this, android.R.layout.simple_spinner_item, saleTypeList);
		saleTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spiSaleType.setAdapter(saleTypeAdapter);

		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);

		if (null != dataCollectSaleInfo) {
			txtSKUId.setText(dataCollectSaleInfo.getBismt_prom());
			txtApplyForSale.setText(dataCollectSaleInfo.getPsaleprice());
			txtExecSale.setText(dataCollectSaleInfo.getPromprice());
			btnStartDateModify.setText(dataCollectSaleInfo.getBdate());
			btnEndDataModify.setText(dataCollectSaleInfo.getEdate());
			if ("Y".equals(dataCollectSaleInfo.getTg())) {
				chkIsTG.setChecked(true);
			}
			if ("Y".equals(dataCollectSaleInfo.getTicket())) {
				chkIsSaleTablet.setChecked(true);
			}
			txtEffect.setText(dataCollectSaleInfo.getPromremark());
			status = "modify";
			oldSku = dataCollectSaleInfo.getBismt_prom();
			spiUnit.setSelection(getSpinnerSelectedItemPosition(dataCollectSaleInfo.getUnitInfo()),
					true);
			spiSaleType.setSelection(
					getSpinnerSelectedItemPosition(dataCollectSaleInfo.getSaleType()), true);
		} else {
			btnStartDateModify.setText(vsdate);
			btnEndDataModify.setText(vsdate);
			dataCollectSaleInfo = new DataCollectSaleInfoBean();
			status = "add";
		}

	}

	private void addListener() {
		txtSKUId.setKeyListener(CommonUtil.charNumListener);
		txtSKUId.setOnFocusChangeListener(new OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				String str = ((EditText) v).getText().toString();
				if (!hasFocus && !"".equals(str)) {
					txtSKUId.setText(str.toUpperCase());
				}
			}
		});

		spiUnit.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				UnitInfoBean bean = (UnitInfoBean) parent.getItemAtPosition(position);
				dataCollectSaleInfo.setUnitInfo(bean);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}

		});

		spiSaleType.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				SaleTypeBean bean = (SaleTypeBean) parent.getItemAtPosition(position);
				dataCollectSaleInfo.setSaleType(bean);

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}

		});

		btnStartDateModify.setOnClickListener(btnListenerEvent);
		btnEndDataModify.setOnClickListener(btnListenerEvent);
		btnSave.setOnClickListener(btnListenerEvent);
		btnBack.setOnClickListener(btnListenerEvent);
	}

	private boolean getData() {
		String sKUIdStr = txtSKUId.getText().toString().trim();
		if (null == sKUIdStr || "".equals(sKUIdStr)) {
			Toast.makeText(DataCollectSale.this, "请输入促销SKU!!", Toast.LENGTH_SHORT).show();
			return false;
		}
		dataCollectSaleInfo.setBismt_prom(sKUIdStr.toUpperCase());

		String applyForSaleStr = txtApplyForSale.getText().toString().trim();
		if (null == applyForSaleStr || "".equals(applyForSaleStr)
				|| Double.parseDouble(applyForSaleStr) == 0) {
			Toast.makeText(DataCollectSale.this, "请输入申请售价或者申请售价不能为0!", Toast.LENGTH_SHORT).show();
			return false;
		}
		dataCollectSaleInfo.setPsaleprice(applyForSaleStr);

		String execSaleStr = txtExecSale.getText().toString().trim();
		if (null == execSaleStr || "".equals(execSaleStr) || Double.parseDouble(execSaleStr) == 0) {
			Toast.makeText(DataCollectSale.this, "请输入执行售价或者执行售价不能为0!", Toast.LENGTH_SHORT).show();
			return false;
		}
		dataCollectSaleInfo.setPromprice(execSaleStr);

		dataCollectSaleInfo.setBdate(btnStartDateModify.getText().toString());
		dataCollectSaleInfo.setEdate(btnEndDataModify.getText().toString());
		if (chkIsTG.isChecked()) {
			dataCollectSaleInfo.setTg("Y");
		} else {
			dataCollectSaleInfo.setTg("N");
		}

		if (chkIsSaleTablet.isChecked()) {
			dataCollectSaleInfo.setTicket("Y");
		} else {
			dataCollectSaleInfo.setTicket("N");
		}
		dataCollectSaleInfo.setPromremark(txtEffect.getText().toString().trim());
		dataCollectSaleInfo.setVsdate(vsdate);
		return true;

	}

	private View.OnClickListener btnListenerEvent = new View.OnClickListener() {

		public void onClick(View v) {
			Button button = (Button) v;
			switch (button.getId()) {
				case R.id.btnStartDateModify :
					showDialog(R.id.btnStartDateModify);
					break;
				case R.id.btnEndDataModify :
					showDialog(R.id.btnEndDataModify);
					break;
				case R.id.btnBack :
					DataCollectSale.this.finish();
					break;
				case R.id.btnSave :
					if (!getData()) {
						return;
					}
					try {
						if (!checkDate(dataCollectSaleInfo.getBdate(),
								dataCollectSaleInfo.getEdate())) {
							return;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					if ("add".equals(status)) {
						for (int i = 0; i < dataCollectSaleInfoList.size(); i++) {
							if (dataCollectSaleInfo.getBismt_prom().equals(
									dataCollectSaleInfoList.get(i).getBismt_prom())) {
								Toast.makeText(DataCollectSale.this, "不能添加重复的SKU!",
										Toast.LENGTH_SHORT).show();
								return;
							}
						}
					} else if ("modify".equals(status)) {
						if (!oldSku.equals(dataCollectSaleInfo.getBismt_prom())) {
							for (int i = 0; i < dataCollectSaleInfoList.size(); i++) {
								if (dataCollectSaleInfo.getBismt_prom().equals(
										dataCollectSaleInfoList.get(i).getBismt_prom())) {
									Toast.makeText(DataCollectSale.this, "不能添加重复的SKU!",
											Toast.LENGTH_SHORT).show();
									return;
								}
							}
						}
					}
					bundle = new Bundle();
					bundle.putSerializable("dataCollectSaleInfo", dataCollectSaleInfo);
					bundle.putInt("dataCollSalePosition", dataCollSalePosition);
					intent = new Intent();
					intent.putExtras(bundle);
					DataCollectSale.this.setResult(RESULT_OK, intent);
					DataCollectSale.this.finish();
					break;
			}
		}
	};

	private OnDateSetListener startDateLis = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			String monthStr = "01";
			String dayStr = "01";
			if (mMonth + 1 < 10) {
				monthStr = "0" + (mMonth + 1);
			} else {
				monthStr = (mMonth + 1) + "";
			}
			mDay = dayOfMonth;
			if (mDay < 10) {
				dayStr = "0" + mDay;
			} else {
				dayStr = mDay + "";
			}
			btnStartDateModify.setText(mYear + "-" + monthStr + "-" + dayStr);
		}
	};
	private OnDateSetListener endDateLis = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			String monthStr = "01";
			String dayStr = "01";
			if (mMonth + 1 < 10) {
				monthStr = "0" + (mMonth + 1);
			} else {
				monthStr = (mMonth + 1) + "";
			}
			mDay = dayOfMonth;
			if (mDay < 10) {
				dayStr = "0" + mDay;
			} else {
				dayStr = mDay + "";
			}
			btnEndDataModify.setText(mYear + "-" + monthStr + "-" + dayStr);
		}
	};

	private boolean checkDate(String startDateStr, String endDateStr) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = format.parse(startDateStr);
		Date endDate = format.parse(endDateStr);
		int result = startDate.compareTo(endDate);
		if (result == 1) {
			Toast.makeText(DataCollectSale.this, "开始日期必须小于结束日期!", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case R.id.btnStartDateModify :
				return new DatePickerDialog(this, startDateLis, mYear, mMonth, mDay);
			case R.id.btnEndDataModify :
				return new DatePickerDialog(this, endDateLis, mYear, mMonth, mDay);
		}
		return null;
	}

	private int getSpinnerSelectedItemPosition(UnitInfoBean unitInfo) {
		int position = 0;
		for (int i = 0; i < unitInfoList.size(); i++) {
			if (unitInfo.getUnit().equals(unitInfoList.get(i).getUnit())) {
				position = i;
			}
		}
		return position;
	}

	private int getSpinnerSelectedItemPosition(SaleTypeBean saleType) {
		int position = 0;
		for (int i = 0; i < saleTypeList.size(); i++) {
			if (saleType.getJg().equals(saleTypeList.get(i).getJg())) {
				position = i;
			}
		}
		return position;
	}

}
